<template>
  <div class="tab-bar">
    <!-- 左滚动按钮 -->
    <div 
      class="scroll-button scroll-left" 
      @click="scrollTabs('left')"
      v-show="showScrollButtons && canScrollLeft"
    >
      <i class="scroll-icon">◀</i>
    </div>
    
    <div class="tab-list" 
      ref="tabListRef"
      @touchstart="handleTouchStart"
      @touchend="handleTouchEnd"
      @scroll="handleScroll"
    >
      <el-tooltip
        v-for="tab in tabs"
        :key="tab.path"
        :content="tab.title || tab.name || '未知页面'"
        placement="top"
        :enterable="false"
        :show-after="800"
        effect="light"
      >
        <div
          class="tab-item"
          :class="{ 
            'active': tab.path === activeTab,
            'fixed': tab.fixed,
            'micro-app': isMicroAppTab(tab.path)
          }"
          @click="handleTabClick(tab)"
          @contextmenu.prevent="openContextMenu($event, tab)"
        >
          <i v-if="tab.icon" :class="tab.icon" class="tab-icon"></i>
          <span class="tab-title">{{ tab.title || tab.name || '未知页面' }}</span>
          <i 
            v-if="!tab.fixed" 
            class="close-icon" 
            @click.stop="handleCloseTabWithLimit(tab)"
          >
            ×
          </i>
          <i 
            v-if="tab.fixed" 
            class="fixed-icon"
            @click.stop="toggleFixTab(tab)"
          >
            📌
          </i>
        </div>
      </el-tooltip>
    </div>
    
    <!-- 右滚动按钮 -->
    <div 
      class="scroll-button scroll-right" 
      @click="scrollTabs('right')"
      v-show="showScrollButtons && canScrollRight"
    >
      <i class="scroll-icon">▶</i>
    </div>
    
    <!-- 右键菜单 -->
    <div 
      v-show="contextMenuVisible" 
      class="tab-context-menu"
      :style="contextMenuStyle"
    >
      <div class="context-item" @click="refreshTab">
        <i class="context-icon">⟳</i> 刷新当前页面
      </div>
      <div class="context-item" @click="closeCurrentTab" v-if="!contextTab.fixed">
        <i class="context-icon">×</i> 关闭当前标签
      </div>
      <div class="context-item" @click="toggleFixCurrentTab">
        <i class="context-icon">📌</i> {{ contextTab.fixed ? '取消固定' : '固定标签' }}
      </div>
      <div class="context-divider"></div>
      <div class="context-item" @click="closeOtherTabs">
        <i class="context-icon">⊖</i> 关闭其他标签
      </div>
      <div class="context-item" @click="closeAllTabs">
        <i class="context-icon">⊗</i> 关闭全部标签
      </div>
      <div class="context-divider"></div>
      <div class="context-item" @click="closeLeftTabs">
        <i class="context-icon">◀</i> 关闭左侧标签
      </div>
      <div class="context-item" @click="closeRightTabs">
        <i class="context-icon">▶</i> 关闭右侧标签
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useTabStore } from '../store/tab'
import { usePermissionStore } from '../store/permission'
import type { TabItem } from '../store/tab'
import { isMicroAppPath } from '../utils/microAppHelper'
import { ElMessageBox, ElMessage } from 'element-plus'

const tabStore = useTabStore()
const permissionStore = usePermissionStore()
const router = useRouter()
const tabListRef = ref<HTMLElement>()

// 滚动按钮状态
const showScrollButtons = ref(false)
const canScrollLeft = ref(false)
const canScrollRight = ref(false)

const tabs = computed(() => {
  // 过滤没有权限的标签
  return tabStore.tabs.filter(tab => {
    if (tab.permission) {
      return permissionStore.hasPermission(tab.permission)
    }
    return true
  })
})
const activeTab = computed(() => tabStore.activeTab)

// 监听滚动事件，更新按钮状态
const handleScroll = () => {
  if (tabListRef.value) {
    const { scrollLeft, scrollWidth, clientWidth } = tabListRef.value
    canScrollLeft.value = scrollLeft > 0
    canScrollRight.value = scrollLeft < (scrollWidth - clientWidth)
  }
}

// 检查是否需要显示滚动按钮
const checkScrollButtonsVisibility = () => {
  if (tabListRef.value) {
    showScrollButtons.value = tabListRef.value.scrollWidth > tabListRef.value.clientWidth
    handleScroll() // 更新左右按钮状态
  }
}

// 滚动标签列表
const scrollTabs = (direction: 'left' | 'right') => {
  if (!tabListRef.value) return
  
  const scrollAmount = tabListRef.value.clientWidth / 2
  const scrollTo = direction === 'left' 
    ? tabListRef.value.scrollLeft - scrollAmount
    : tabListRef.value.scrollLeft + scrollAmount
  
  tabListRef.value.scrollTo({
    left: scrollTo,
    behavior: 'smooth'
  })
}

const isMicroAppTab = (path: string) => {
  return isMicroAppPath(path)
}

const handleTabClick = (tab: TabItem) => {
  router.push(tab.path)
}

const handleCloseTab = (tab: TabItem) => {
  // 关闭标签
  tabStore.removeTab(tab.path)
}

// 防止频繁点击关闭按钮
const handleCloseTabWithLimit = (tab: TabItem) => {
  // 简单防抖处理
  if (isClosingTab.value) return
  isClosingTab.value = true
  handleCloseTab(tab)
  setTimeout(() => {
    isClosingTab.value = false
  }, 200)
}

const isClosingTab = ref(false)

const toggleFixTab = (tab: TabItem) => {
  tabStore.toggleFixTab(tab.path, !tab.fixed)
}

const handleCloseOther = () => {
  tabStore.removeOther()
}

const handleCloseAll = () => {
  // 获取固定的标签
  const fixedTabs = tabs.value.filter(tab => tab.fixed)
  
  // 更新标签列表，保留固定标签
  tabStore.setTabs(fixedTabs)
  
  // 如果有固定标签，跳转到第一个固定标签
  // 否则跳转到首页
  if (fixedTabs.length > 0) {
    router.push(fixedTabs[0].path)
  } else {
    router.push('/')
  }
}

// 右键菜单逻辑
const contextMenuVisible = ref(false)
const contextMenuStyle = ref({
  top: '0px',
  left: '0px'
})
const contextTab = ref<TabItem>({} as TabItem)

const openContextMenu = (event: MouseEvent, tab: TabItem) => {
  event.preventDefault()
  contextMenuVisible.value = true
  contextMenuStyle.value = {
    top: `${event.clientY}px`,
    left: `${event.clientX}px`
  }
  contextTab.value = tab
  
  // 添加点击外部关闭菜单的事件监听
  setTimeout(() => {
    window.addEventListener('click', closeContextMenu)
  }, 0)
}

const closeContextMenu = () => {
  contextMenuVisible.value = false
  window.removeEventListener('click', closeContextMenu)
}

// 右键菜单操作
const refreshTab = () => {
  tabStore.reloadTab(contextTab.value.path, contextTab.value.keepAlive)
  closeContextMenu()
}

const closeCurrentTab = () => {
  if (!contextTab.value.fixed) {
    handleCloseTab(contextTab.value)
  }
  closeContextMenu()
}

const toggleFixCurrentTab = () => {
  tabStore.toggleFixTab(contextTab.value.path, !contextTab.value.fixed)
  closeContextMenu()
}

const closeOtherTabs = () => {
  tabStore.removeOther(contextTab.value.path)
  closeContextMenu()
}

const closeAllTabs = () => {
  handleCloseAll()
  closeContextMenu()
}

const closeLeftTabs = () => {
  tabStore.removeLeft(contextTab.value.path)
  closeContextMenu()
}

const closeRightTabs = () => {
  tabStore.removeRight(contextTab.value.path)
  closeContextMenu()
}

// 键盘快捷键
const setupKeyboardShortcuts = () => {
  const handleKeyDown = (event: KeyboardEvent) => {
    // Ctrl+W 关闭当前标签
    if (event.ctrlKey && event.key === 'w') {
      event.preventDefault()
      const currentTab = tabs.value.find(tab => tab.path === activeTab.value)
      if (currentTab && !currentTab.fixed) {
        handleCloseTab(currentTab)
      }
      return
    }
    
    // Ctrl+Tab 切换到下一个标签
    if (event.ctrlKey && event.key === 'Tab' && !event.shiftKey) {
      event.preventDefault()
      const index = tabs.value.findIndex(tab => tab.path === activeTab.value)
      if (index > -1 && tabs.value.length > 1) {
        const nextIndex = (index + 1) % tabs.value.length
        router.push(tabs.value[nextIndex].path)
      }
      return
    }
    
    // Ctrl+Shift+Tab 切换到上一个标签
    if (event.ctrlKey && event.key === 'Tab' && event.shiftKey) {
      event.preventDefault()
      const index = tabs.value.findIndex(tab => tab.path === activeTab.value)
      if (index > -1 && tabs.value.length > 1) {
        const prevIndex = (index - 1 + tabs.value.length) % tabs.value.length
        router.push(tabs.value[prevIndex].path)
      }
      return
    }
    
    // Alt+数字键 快速切换到对应位置的标签 (Alt+1, Alt+2, ...)
    if (event.altKey && !isNaN(parseInt(event.key)) && event.key >= '1' && event.key <= '9') {
      const tabIndex = parseInt(event.key) - 1
      if (tabIndex < tabs.value.length) {
        event.preventDefault()
        router.push(tabs.value[tabIndex].path)
      }
    }
  }
  
  window.addEventListener('keydown', handleKeyDown)
  
  return () => {
    window.removeEventListener('keydown', handleKeyDown)
  }
}

// 滚动标签栏到当前活动标签可见
const scrollToActiveTab = () => {
  nextTick(() => {
    if (tabListRef.value) {
      const activeTabElement = tabListRef.value.querySelector('.tab-item.active')
      if (activeTabElement) {
        // 计算滚动位置，使活动标签居中
        const container = tabListRef.value
        const containerWidth = container.clientWidth
        const tabWidth = activeTabElement.clientWidth
        const tabLeft = (activeTabElement as HTMLElement).offsetLeft
        
        container.scrollLeft = tabLeft - (containerWidth / 2) + (tabWidth / 2)
      }
      
      // 检查滚动按钮可见性
      checkScrollButtonsVisibility()
    }
  })
}

// 监视活动标签的变化，滚动到可见区域
watch(() => activeTab.value, () => {
  scrollToActiveTab()
})

// 监视标签数量变化，更新滚动按钮状态
watch(() => tabs.value.length, () => {
  nextTick(() => {
    checkScrollButtonsVisibility()
  })
})

// 触摸滑动相关
const touchStartX = ref(0)
const touchEndX = ref(0)
const MIN_SWIPE_DISTANCE = 80 // 最小滑动距离，单位像素

const handleTouchStart = (event: TouchEvent) => {
  touchStartX.value = event.touches[0].clientX
}

const handleTouchEnd = (event: TouchEvent) => {
  touchEndX.value = event.changedTouches[0].clientX
  handleSwipe()
}

const handleSwipe = () => {
  const swipeDistance = touchEndX.value - touchStartX.value
  if (Math.abs(swipeDistance) < MIN_SWIPE_DISTANCE) return
  
  const index = tabs.value.findIndex(tab => tab.path === activeTab.value)
  if (index === -1 || tabs.value.length <= 1) return
  
  if (swipeDistance > 0) {
    // 右滑，切换到前一个标签
    const prevIndex = (index - 1 + tabs.value.length) % tabs.value.length
    router.push(tabs.value[prevIndex].path)
  } else {
    // 左滑，切换到下一个标签
    const nextIndex = (index + 1) % tabs.value.length
    router.push(tabs.value[nextIndex].path)
  }
}

// 鼠标滚轮控制水平滚动
const handleWheel = (event: WheelEvent) => {
  // 阻止默认的垂直滚动
  if (event.deltaX === 0 && tabListRef.value) {
    event.preventDefault()
    tabListRef.value.scrollLeft += event.deltaY
  }
}

// 组件挂载和卸载生命周期
onMounted(() => {
  const cleanup = setupKeyboardShortcuts()
  
  // 初始化滚动和检查按钮可见性
  scrollToActiveTab()
  window.addEventListener('resize', checkScrollButtonsVisibility)
  
  // 添加触摸事件监听
  const tabList = tabListRef.value
  if (tabList) {
    tabList.addEventListener('touchstart', handleTouchStart)
    tabList.addEventListener('touchend', handleTouchEnd)
    tabList.addEventListener('wheel', handleWheel, { passive: false })
  }
  
  onBeforeUnmount(() => {
    cleanup()
    window.removeEventListener('resize', checkScrollButtonsVisibility)
    
    // 移除事件监听
    if (tabList) {
      tabList.removeEventListener('touchstart', handleTouchStart)
      tabList.removeEventListener('touchend', handleTouchEnd)
      tabList.removeEventListener('wheel', handleWheel)
    }
  })
})
</script>

<style scoped>
.tab-bar {
  display: flex;
  align-items: center;
  background: var(--card-background-color);
  border-bottom: 1px solid var(--border-color-light);
  padding: 0 16px;
  height: 40px;
}

.scroll-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: var(--border-color-light);
  cursor: pointer;
  user-select: none;
  z-index: 2;
  transition: all 0.2s;
  flex-shrink: 0;
}

.scroll-button:hover {
  background: var(--border-color);
}

.scroll-icon {
  font-size: 10px;
  color: var(--text-color);
}

.scroll-left {
  margin-right: 8px;
}

.scroll-right {
  margin-left: 8px;
}

.tab-list {
  display: flex;
  flex: 1;
  overflow-x: auto;
  gap: 4px;
  scroll-behavior: smooth; /* 平滑滚动 */
  -webkit-overflow-scrolling: touch; /* 提升移动设备上的滚动体验 */
  white-space: nowrap;
  padding-bottom: 4px; /* 添加一点底部内边距，避免滚动条遮挡 */
}

/* 隐藏滚动条但保持功能 */
.tab-list::-webkit-scrollbar {
  height: 4px;
}

.tab-list::-webkit-scrollbar-track {
  background: transparent;
}

.tab-list::-webkit-scrollbar-thumb {
  background: var(--border-color);
  border-radius: 4px;
}

.tab-list:hover::-webkit-scrollbar-thumb {
  background: var(--border-color-light);
}

.tab-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background-color: var(--el-border-color);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 120px;
  max-width: 200px;
  position: relative;
  user-select: none; /* 防止文本被选中 */
  touch-action: pan-x; /* 优化触摸体验 */
}

.tab-item:hover {
  background: var(--border-color);
}

.tab-item.active {
  background: var(--primary-color);
  color: white;
}

.tab-item.fixed {
  background: #fef3c7;
}

.tab-item.micro-app {
  border-left: 3px solid var(--accent-color);
}

.tab-item.micro-app.active {
  background: var(--accent-color);
  color: white;
}

.tab-icon {
  margin-right: 4px;
  font-size: 14px;
}

.tab-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 12px;
}

.close-icon {
  margin-left: 4px;
  font-size: 14px;
  opacity: 0.6;
  transition: opacity 0.2s;
}

.close-icon:hover {
  opacity: 1;
}

.fixed-icon {
  margin-left: 4px;
  font-size: 12px;
  opacity: 0.8;
}

.tab-actions {
  display: flex;
  gap: 8px;
  margin-left: 16px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  background: linear-gradient(135deg, var(--card-background-color) 0%, var(--border-color-light) 100%);
  border: 1px solid var(--border-color-light);
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
  color: var(--text-color);
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  user-select: none;
}

.action-btn:hover {
  background: linear-gradient(135deg, var(--border-color-light) 0%, var(--border-color) 100%);
  border-color: var(--border-color);
  color: var(--text-color);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transform: translateY(-1px);
}

.action-btn:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.action-icon {
  font-size: 14px;
  font-weight: bold;
  opacity: 0.8;
}

.action-btn:hover .action-icon {
  opacity: 1;
}

/* 右键菜单样式 */
.tab-context-menu {
  position: fixed;
  z-index: 1000;
  min-width: 180px;
  background: var(--card-background-color);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-md);
  padding: 8px 0;
  user-select: none;
  border: 1px solid var(--border-color);
}

.context-item {
  padding: 8px 16px;
  font-size: 13px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
  color: var(--text-color);
}

.context-item:hover {
  background: var(--border-color-light);
  color: var(--primary-color);
}

.context-icon {
  margin-right: 8px;
  font-size: 14px;
  opacity: 0.7;
}

.context-item:hover .context-icon {
  opacity: 1;
}

.context-divider {
  margin: 4px 0;
  height: 1px;
  background: var(--border-color-light);
}
</style> 